package br.net.woodstock.tickettoride.client.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import br.net.woodstock.tickettoride.client.TicketConverter;
import br.net.woodstock.tickettoride.client.TicketException;
import br.net.woodstock.tickettoride.client.utils.CodecUtils;

public class MapTicketConverter implements TicketConverter<Map<String, String>> {

	private static final String	NULL_VALUE	= "";

	@Override
	public Map<String, String> fromBytes(final byte[] bytes) {
		try {
			InputStream inputStream = new ByteArrayInputStream(bytes);
			InputStreamReader reader = new InputStreamReader(inputStream, CodecUtils.CHARSET);
			Properties properties = new Properties();
			properties.load(reader);
			Map<String, String> map = new HashMap<String, String>();
			for (Entry<Object, Object> entry : properties.entrySet()) {
				Object value = entry.getValue();
				String strValue = null;
				if (value != null) {
					strValue = value.toString();
				}
				map.put(entry.getKey().toString(), strValue);
			}
			return map;
		} catch (IOException e) {
			throw new TicketException(e);
		}
	}

	@Override
	public byte[] toBytes(final Map<String, String> t) {
		try {
			Properties properties = new Properties();
			for (Entry<String, String> entry : t.entrySet()) {
				Object value = entry.getValue();
				if (value == null) {
					value = MapTicketConverter.NULL_VALUE;
				}
				properties.put(entry.getKey(), value);
			}
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			OutputStreamWriter writer = new OutputStreamWriter(outputStream, CodecUtils.CHARSET);
			properties.store(writer, null);
			return outputStream.toByteArray();
		} catch (IOException e) {
			throw new TicketException(e);
		}
	}

}
